package com.fly.demo.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fly.core.config.SysDataBaseConfig;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * IndexController
 * 
 * @author 00fly
 * @version [版本号, 2018-09-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Api(tags = "演示接口")
@Controller
public class IndexController
{
    @Autowired
    HttpSession session;
    
    @Autowired
    private Producer producer;
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Autowired
    SysDataBaseConfig sysDataBaseConfig;
    
    @GetMapping("/")
    public String index()
    {
        return "redirect:/user/";
    }
    
    @ResponseBody
    @ApiOperation("验证码图片")
    @GetMapping(value = "captcha.jpg", produces = MediaType.IMAGE_JPEG_VALUE)
    public void captcha(HttpServletResponse response)
        throws IOException
    {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType(MediaType.TEXT_HTML_VALUE);
        
        // 生成文字验证码
        String text = producer.createText();
        // 保存到session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream out = response.getOutputStream())
        {
            ImageIO.write(image, "jpg", out);
        }
    }
    
    @ResponseBody
    @ApiOperation("更新系統")
    @PostMapping("update/sysconfig")
    public String update(String key, String value)
    {
        int count = jdbcTemplate.update("update sys_config set `value`=? where `key`=?", value, key);
        sysDataBaseConfig.initDatabasePropertySource();
        return "update success count:" + count;
    }
}
